import React, { useState } from "react";
import data from "../../mock/city (1).json";
import "./style.css";

const citys = data.reduce((p, n) => {
  return p.concat(n.cityList);
}, [] as string[]);

const Index: React.FC = () => {
  const [cityList, setCityList] = useState(data);
  const [isSearch, setIsSearch] = useState(false);
  const [searchText, setSearchText] = useState("");

  const allCity = (
    <div>
      <div className="city">
        <ul>
          {data.map((v, i) => {
            return (
              <li key={i}>
                <h2 id={v.code}>{v.code}</h2>
                <div>
                  {v.cityList.map((v, i) => {
                    return <span key={i}>{v}</span>;
                  })}
                </div>
              </li>
            );
          })}
        </ul>
      </div>
      <div className="first-word">
        {data.map((v, i) => {
          return (
            <a key={i} href={"#" + v.code}>
              {v.code}
            </a>
          );
        })}
      </div>
    </div>
  );

  const searchCity = (
    <ul>
      {citys
        .filter((v) => v.includes(searchText))
        .map((v, i) => {
          return <li key={i}>{v}</li>;
        })}
    </ul>
  );

  const onChange = (value: string) => {
    setSearchText(value);
    setIsSearch(true);
  };

  return (
    <div>
      <header>
        <input
          type="text"
          className="search"
          placeholder="请搜索城市"
          onKeyDown={(e) =>
            e.keyCode === 13 && onChange((e.target as any).value)
          }
          value={searchText}
          onChange={(e) => setSearchText(e.target.value)}
        />
        <span
          onClick={() => {
            setSearchText("");
            setIsSearch(false);
          }}
        >
          取消
        </span>
      </header>
      {isSearch ? searchCity : allCity}
    </div>
  );
};

export default Index;
